<!DOCTYPE html>


<html lang="zh-Hans">


<head>
  <meta charset="utf-8" />
   
  <meta name="keywords" content="代码,生活,杂记,思考" />
   
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    事件 |  AURORA
  </title>
  <meta name="generator" content="hexo-theme-ayer">
  
  <link rel="shortcut icon" href="/favicon.ico" />
  
  
<link rel="stylesheet" href="/dist/main.css">

  
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/Shen-Yu/cdn/css/remixicon.min.css">

  
<link rel="stylesheet" href="/css/custom.css">

  
  
<script src="https://cdn.jsdelivr.net/npm/pace-js@1.0.2/pace.min.js"></script>

  
  

  

<link rel="alternate" href="/atom.xml" title="AURORA" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    
      
    <main class="content on">
      <section class="outer">
  <article
  id="post-事件"
  class="article article-type-post"
  itemscope
  itemprop="blogPost"
  data-scroll-reveal
>
  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  事件
</h1>
 

    </header>
     
    <div class="article-meta">
      <a href="/2020/02/11/%E4%BA%8B%E4%BB%B6/" class="article-date">
  <time datetime="2020-02-10T16:00:00.000Z" itemprop="datePublished">2020-02-11 00:02:00</time>
</a> 
  <div class="article-category">
    <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/">技术</a> / <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/%E5%89%8D%E7%AB%AF/">前端</a> / <a class="article-category-link" href="/categories/%E6%8A%80%E6%9C%AF/%E5%89%8D%E7%AB%AF/JavaScript/">JavaScript</a>
  </div>
  
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> Word count:</span>
            <span class="post-count">2.6k</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> Reading time≈</span>
            <span class="post-count">10 min</span>
        </span>
    </span>
</div>
 
    </div>
      
    <div class="tocbot"></div>




  
    <div class="article-entry" itemprop="articleBody">
       
  <h1 id="事件"><a href="#事件" class="headerlink" title="事件"></a>事件</h1><a id="more"></a>
<p>JavaScript与HTML之间的交互是通过事件实现的。可以使用一些侦听器来预定事件，以便在事件发生时执行相应的代码。</p>
<h2 id="事件冒泡"><a href="#事件冒泡" class="headerlink" title="事件冒泡"></a>事件冒泡</h2><p>事件一开始时由具体的元素接收，然后向上传播到较为不具体的节点。例如我们点击一个按钮时，就会产生一个click事件，但这个按钮本身可能不能处理这个事件，事件必须从这个按钮传播出去，从而到达能够处理这个事件的代码中（例如我们给按钮的onclick属性赋一个函数的名字，就是让这个函数去处理该按钮的click事件），或者按钮的父级绑定有事件函数，当该点击事件发生在按钮上，按钮本身并无处理事件函数，则传播到父级去处理。</p>
<h2 id="事件捕获"><a href="#事件捕获" class="headerlink" title="事件捕获"></a>事件捕获</h2><p>从不太具体的节点更早接收事件，而最具体的节点最后接收到事件。事件捕获的目的在于事件到达预定目标之前捕获它。即自上而下的去触发事件</p>
<h2 id="事件流"><a href="#事件流" class="headerlink" title="事件流"></a>事件流</h2><p><img src="https://img-blog.csdn.net/20180909183557914?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xpdG9uZzE0OQ==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt=""><br>“DOM2级事件”规定的事件流包括三个阶段：</p>
<ol>
<li>事件捕获阶段</li>
<li>处于目标阶段</li>
<li><p>事件冒泡阶段</p>
<p>上面这个图就描述了一个事件按如上这个顺序进行触发。</p>
<p>如果要测试上面这个顺序，先来了解<strong>DOM2级事件处理程序</strong></p>
</li>
</ol>
<h3 id="DOM2级事件处理——addEventListener"><a href="#DOM2级事件处理——addEventListener" class="headerlink" title="DOM2级事件处理——addEventListener"></a>DOM2级事件处理——addEventListener</h3><p>addEventListener是DOM2级事件新增的指定事件处理程序的操作，这个方法接收3个参数：要处理的事件名，作为事件处理程序的函数和一个布尔值，最后这个布尔值如果是true，表示在捕获阶段调用事件处理程序；如果是false，表示在冒泡阶段调用事件处理程序。默认情况下第二个参数值为false，也就是说DOM2级事件处理程序默认是在冒泡阶段处理事件。<br>通过addEventListener添加的事件处理程序只能通过removeEventListener()来移除</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">window.onload &#x3D; function()&#123;</span><br><span class="line"></span><br><span class="line">        var oBtn &#x3D; document.getElementById(&#39;btn&#39;);</span><br><span class="line">        oBtn.addEventListener(&#39;click&#39;,function()&#123;</span><br><span class="line">            console.log(&#39;btn处于事件捕获阶段&#39;);</span><br><span class="line">        &#125;, true);</span><br><span class="line">        oBtn.addEventListener(&#39;click&#39;,function()&#123;</span><br><span class="line">            console.log(&#39;btn处于事件冒泡阶段&#39;);</span><br><span class="line">        &#125;, false);</span><br><span class="line"></span><br><span class="line">        document.addEventListener(&#39;click&#39;,function()&#123;</span><br><span class="line">            console.log(&#39;document处于事件捕获阶段&#39;);</span><br><span class="line">        &#125;, true);</span><br><span class="line">        document.addEventListener(&#39;click&#39;,function()&#123;</span><br><span class="line">            console.log(&#39;document处于事件冒泡阶段&#39;);</span><br><span class="line">        &#125;, false);</span><br><span class="line"></span><br><span class="line">        document.documentElement.addEventListener(&#39;click&#39;,function()&#123;</span><br><span class="line">            console.log(&#39;html处于事件捕获阶段&#39;);</span><br><span class="line">        &#125;, true);</span><br><span class="line">        document.documentElement.addEventListener(&#39;click&#39;,function()&#123;</span><br><span class="line">            console.log(&#39;html处于事件冒泡阶段&#39;);</span><br><span class="line">        &#125;, false);</span><br><span class="line"></span><br><span class="line">        document.body.addEventListener(&#39;click&#39;,function()&#123;</span><br><span class="line">            console.log(&#39;body处于事件捕获阶段&#39;);</span><br><span class="line">        &#125;, true);</span><br><span class="line">        document.body.addEventListener(&#39;click&#39;,function()&#123;</span><br><span class="line">            console.log(&#39;body处于事件冒泡阶段&#39;);</span><br><span class="line">        &#125;, false);</span><br><span class="line"></span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F;html</span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;a href&#x3D;&quot;javascript:;&quot; id&#x3D;&quot;btn&quot;&gt;按钮&lt;&#x2F;a&gt;</span><br><span class="line">&lt;&#x2F;body&gt;</span><br></pre></td></tr></table></figure>
<p>效果<br><img src="https://imgconvert.csdnimg.cn/aHR0cHM6Ly9pbWFnZXMyMDE4LmNuYmxvZ3MuY29tL2Jsb2cvMTM1MzYwOC8yMDE4MDYvMTM1MzYwOC0yMDE4MDYwNDE2NDQwMjEyNy01MzM5NDg2NjEucG5n?x-oss-process=image/format,png" alt="在这里插入图片描述"></p>
<h3 id="HTML事件处理程序"><a href="#HTML事件处理程序" class="headerlink" title="HTML事件处理程序"></a>HTML事件处理程序</h3><p>某个元素支持某种事件，都可以使用一个与相应事件处理程序同名的HTML特性来指定，这个特性的值应该是能够执行的javascript代码。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type = <span class="string">"button"</span> onclick = <span class="string">"alert('click')"</span>&gt;</span><br></pre></td></tr></table></figure>
<p>这个操作通过指定onclick特性并将一些javascript代码作为它的值来定义。因此不能再其中使用未经过转义的html语法字符，例如&amp;，””，&lt;&gt;。</p>
<p>html事件处理程序可以包含具体的动作，也可以调用其他地方定义的脚本</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">showMessage</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">		alert(<span class="string">'click'</span>);</span><br><span class="line">	&#125;</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;input type = "button" onclick = "showMessage()"&gt;</span></span><br></pre></td></tr></table></figure>
<p>这样指定事件处理程序有一个独到之处。首先会<strong>创建</strong>一个封装着元素属性值的函数，这个函数中有一个局部变量event，也就是<strong>事件对象</strong>。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type = <span class="string">"button"</span> onclick = <span class="string">"alert(event.tyep)"</span>&gt;</span><br><span class="line"><span class="comment">//click</span></span><br></pre></td></tr></table></figure>
<p>通过event变量，可以直接访问事件对象，在这个函数内部，this的值等于<strong>事件的目标元素</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type = <span class="string">"button"</span> value = <span class="string">"click me"</span> onclick = <span class="string">"alert(this.value)"</span>&gt;</span><br><span class="line"><span class="comment">//click me</span></span><br></pre></td></tr></table></figure>
<p>关于这样动态创建的函数，在这个函数的内部，可以像访问局部变量一样访问document及该元素本身的成员。前提是这个函数使用with像这样<strong>扩展作用域链</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">with</span>(<span class="built_in">document</span>)&#123;</span><br><span class="line">		<span class="keyword">with</span>(<span class="keyword">this</span>)&#123;</span><br><span class="line">			<span class="comment">//...</span></span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样访问自己的属性就简单多了</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;script&gt;</span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">showMessage</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">		<span class="keyword">with</span>(<span class="built_in">document</span>)&#123;</span><br><span class="line">			<span class="keyword">with</span>(<span class="keyword">this</span>)&#123;</span><br><span class="line">				<span class="comment">//...</span></span><br><span class="line">				<span class="keyword">var</span> val = value</span><br><span class="line">		&#125;</span><br><span class="line">		alert(val)<span class="comment">//hhh</span></span><br><span class="line">	&#125;</span><br><span class="line">&lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;input type = "button" value = "hhh" onclick = "showMessage()"&gt;</span></span><br></pre></td></tr></table></figure>
<h4 id="html事件处理的缺点"><a href="#html事件处理的缺点" class="headerlink" title="html事件处理的缺点"></a>html事件处理的缺点</h4><p><strong>时差问题：</strong><br>以上面的栗子，如果在showMessage()解析之前就单击了按钮触发了事件，就会引发错误。因此，很多html事件都会被封装在try-catch中，因此上面的代码实际上是这样的</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type = <span class="string">"button"</span> value = <span class="string">"hhh"</span> onclick = <span class="string">"try&#123;showMessage()&#125;catch(er)&#123;&#125;"</span>&gt;</span><br></pre></td></tr></table></figure>
<p>因此就算发生这种情况，用户也看不到js的报错提示</p>
<p><strong>扩展事件处理程序的作用域链在不同浏览器中会导致不同的结果</strong></p>
<p><strong>HTML和javascript代码紧耦合，不利于后期代码维护</strong></p>
<h3 id="DOM0级事件处理程序"><a href="#DOM0级事件处理程序" class="headerlink" title="DOM0级事件处理程序"></a>DOM0级事件处理程序</h3><p>将函数赋值给一个事件处理程序属性。首先获取一个要操作的对象的<strong>引用</strong>。每个元素都有自己的时间处理程序属性</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> btn = <span class="built_in">document</span>.getElementById(<span class="string">'myBtn'</span>)</span><br><span class="line">btn.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	alert(<span class="string">'hhh'</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>注意：使用DOM0级事件处理程序被认为是元素的方法，这个时候事件处理程序是在元素的作用域中运行，换句话说这时函数的this指向当前元素</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type = <span class="string">"button"</span> value = <span class="string">"hhh"</span> id  = <span class="string">"myBtn"</span>&gt;</span><br><span class="line"><span class="keyword">var</span> btn = <span class="built_in">document</span>.getElementById(<span class="string">'myBtn'</span>)</span><br><span class="line">btn.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	alert(<span class="keyword">this</span>.id)<span class="comment">//myBtn</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>实际上可以在事件处理程序中访问元素的任何属性和方法，<strong>以这种方式添加的事件处理程序会在事件流的冒泡阶段被处理执行</strong></p>
<p>可以删除DOM0级方法指定的事件处理程序</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">btn.onclick = <span class="literal">null</span></span><br></pre></td></tr></table></figure>
<h2 id="事件对象"><a href="#事件对象" class="headerlink" title="事件对象"></a>事件对象</h2><p>在触发DOM上某个事件，会产生一个事件对象，包含所有与时间有关的信息。<br>无论指定事件处理程序使用DOM0还是DOM2，都会传入event对象</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> btn = <span class="built_in">document</span>.getElementById(<span class="string">'MmyBtn'</span>)</span><br><span class="line">btn.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	alert(event.type)</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//click</span></span><br><span class="line">btn.addEventListener(<span class="string">'click'</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	alert(event.type)</span><br><span class="line">&#125;,<span class="literal">false</span>)</span><br><span class="line"><span class="comment">//click</span></span><br></pre></td></tr></table></figure>
<p>使用html事件处理程序时，也可以直接使用event变量</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;input type = <span class="string">"button"</span> onclick = <span class="string">"alert(event.tyep)"</span>&gt;</span><br></pre></td></tr></table></figure>
<h3 id="event对象的一些属性和方法"><a href="#event对象的一些属性和方法" class="headerlink" title="event对象的一些属性和方法"></a>event对象的一些属性和方法</h3><p><img src="https://img-blog.csdnimg.cn/20200211124400697.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<h3 id="2-级-DOM-事件标准定义的event属性"><a href="#2-级-DOM-事件标准定义的event属性" class="headerlink" title="2 级 DOM 事件标准定义的event属性"></a>2 级 DOM 事件标准定义的event属性</h3><p><img src="https://img-blog.csdnimg.cn/20200211124447922.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTIwMzE5NTg=,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>注意：stopPropagation()    可以立即停止事件在DOM中传播，取消进一步的事件捕获或冒泡。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> btn = <span class="built_in">document</span>.getElementById(<span class="string">'myBtn'</span>)</span><br><span class="line">btn.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	alert(<span class="string">'hhh'</span>)</span><br><span class="line">	event.stopPropagation()</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">document</span>.body.onclick = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	alert(<span class="string">'body click'</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样上面的两个事件处理程序就不会发生冲突</p>
<h2 id="内存与性能"><a href="#内存与性能" class="headerlink" title="内存与性能"></a>内存与性能</h2><p>在javascript中，添加到页面上的事件处理程序将直接关系到页面的整体运行性能。因为每个函数都是对象，都会占用内存；内存中对象越多，性能就越差。其次，必须事先指定所有事件处理程序而导致的DOM访问次数，会延迟整个页面的交互就绪时间。</p>
<h3 id="事件委托"><a href="#事件委托" class="headerlink" title="事件委托"></a>事件委托</h3><p>对于“事件处理程序”过多的解决方案就是事件委托。<strong>事件委托利用了事件冒泡，只指定一个事件处理程序就可以管理某一类型的所有事件。</strong><br>可以大量节省内存占用，减少事件注册，比如在table上代理所有td的click事件就非常棒<br>可以实现当新增子对象时无需再次对其绑定</p>
<h3 id="移除事件处理程序"><a href="#移除事件处理程序" class="headerlink" title="移除事件处理程序"></a>移除事件处理程序</h3><p>一方面可以使用事件委托减少事件处理程序，另一方面可以移除不需要的事件处理程序。<br>有时候，内存中会留有一些过时不用的“空事件处理程序”，这也是造成web应用程序性能降低的主要原因。<br>有两种情况会造成这个问题<br>1、从文档中移除带有事件处理程序的元素时，如果通过纯粹的DOM操作，或innerHTML，那么原来添加到元素中的事件处理程序极有可能无法当做垃圾回收。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;div id = <span class="string">"myDiv"</span>&gt;</span><br><span class="line">	&lt;input type = <span class="string">"button"</span> value = <span class="string">"click me"</span> id = <span class="string">"myBtn"</span>&gt;</span><br><span class="line">&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">&lt;script&gt;</span></span><br><span class="line"><span class="regexp">	var btn = document.getElementById("myBtn")</span></span><br><span class="line"><span class="regexp">	btn.onclick = function()&#123;</span></span><br><span class="line"><span class="regexp">		/</span><span class="regexp">/某些操作</span></span><br><span class="line"><span class="regexp">		document.getElementById('myDiv').innerHTML = ''</span></span><br><span class="line"><span class="regexp">	&#125;</span></span><br><span class="line"><span class="regexp">&lt;/</span>script&gt;</span><br></pre></td></tr></table></figure>
<p>上面这个例子中，点击按钮按钮消失，但问题是当它被移除时还保留着事件处理程序。在div元素上设置innerHTML把按钮移走，但是事件处理程序仍然与按钮保持着引用关系，有的浏览器（比如IE），会把元素和事件处理程序的引用都保存再内存中，不会被移除。因此这种情况下最好手动移除事件处理程序。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">&lt;div id = <span class="string">"myDiv"</span>&gt;</span><br><span class="line">	&lt;input type = <span class="string">"button"</span> value = <span class="string">"click me"</span> id = <span class="string">"myBtn"</span>&gt;</span><br><span class="line">&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">&lt;script&gt;</span></span><br><span class="line"><span class="regexp">	var btn = document.getElementById("myBtn")</span></span><br><span class="line"><span class="regexp">	btn.onclick = function()&#123;</span></span><br><span class="line"><span class="regexp">		/</span><span class="regexp">/某些操作</span></span><br><span class="line"><span class="regexp">		btn.onclick = null</span></span><br><span class="line"><span class="regexp">		document.getElementById('myDiv').innerHTML = ''</span></span><br><span class="line"><span class="regexp">	&#125;</span></span><br><span class="line"><span class="regexp">&lt;/</span>script&gt;</span><br></pre></td></tr></table></figure>
<p>这样写就确保不会占用内存，而DOM中移除按钮也做到了干净利索。<br>同时，在事件处理程序中删除按钮也能组织事件冒泡，<strong>因为目标元素在文档中是事件冒泡的前提</strong>。</p>
<p>2、卸载页面<br>如果页面卸载之前没有清理干净事件处理程序，他们会滞留在内存中。这种情况在IE8以及更早版本IE 和部分其他浏览器问题最突出。最直观的表现就是刷新页面，卸载完页面再重新加载，每刷新一次，内存中滞留的对象数目就会增加，因为事件处理程序占用的内存并没有释放</p>
<p>一般来说最好的解决方案是通过onunload中移除所有事件处理程序</p>
<p><strong>总结</strong>：对于以上两种问题，事件委托都能表现出不错的优势。把需要跟踪的事件处理程序数量减少，可以将解决这个问题变得简单。</p>
 
      <!-- reward -->
      
    </div>
    

    <!-- copyright -->
    
    <div class="declare">
      <ul class="post-copyright">
        <li>
          <i class="ri-copyright-line"></i>
          <strong>Copyright： </strong>
          Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
        </li>
      </ul>
    </div>
    
    <footer class="article-footer">
       
<div class="share-btn">
      <span class="share-sns share-outer">
        <i class="ri-share-forward-line"></i>
        分享
      </span>
      <div class="share-wrap">
        <i class="arrow"></i>
        <div class="share-icons">
          
          <a class="weibo share-sns" href="javascript:;" data-type="weibo">
            <i class="ri-weibo-fill"></i>
          </a>
          <a class="weixin share-sns wxFab" href="javascript:;" data-type="weixin">
            <i class="ri-wechat-fill"></i>
          </a>
          <a class="qq share-sns" href="javascript:;" data-type="qq">
            <i class="ri-qq-fill"></i>
          </a>
          <a class="douban share-sns" href="javascript:;" data-type="douban">
            <i class="ri-douban-line"></i>
          </a>
          <!-- <a class="qzone share-sns" href="javascript:;" data-type="qzone">
            <i class="icon icon-qzone"></i>
          </a> -->
          
          <a class="facebook share-sns" href="javascript:;" data-type="facebook">
            <i class="ri-facebook-circle-fill"></i>
          </a>
          <a class="twitter share-sns" href="javascript:;" data-type="twitter">
            <i class="ri-twitter-fill"></i>
          </a>
          <a class="google share-sns" href="javascript:;" data-type="google">
            <i class="ri-google-fill"></i>
          </a>
        </div>
      </div>
</div>

<div class="wx-share-modal">
    <a class="modal-close" href="javascript:;"><i class="ri-close-circle-line"></i></a>
    <p>扫一扫，分享到微信</p>
    <div class="wx-qrcode">
      <img src="" alt="微信分享二维码">
    </div>
</div>

<div id="share-mask"></div>  
    </footer>
  </div>

   
  <nav class="article-nav">
    
      <a href="/2020/02/11/%E5%AF%B9%E8%B1%A1/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            对象
          
        </div>
      </a>
    
    
      <a href="/2020/02/09/axios%E8%AF%B7%E6%B1%82%E5%B8%A6cookie/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">axios请求带cookie</div>
      </a>
    
  </nav>

   
<!-- valine评论 -->
<div id="vcomments-box">
  <div id="vcomments"></div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/valine@1.4.14/dist/Valine.min.js"></script>
<script>
  new Valine({
    el: "#vcomments",
    app_id: "2eBxdPB3eEwraN7IpwFckzeL-gzGzoHsz",
    app_key: "VGgCefQEluVxHdyMsm1Dpeih",
    path: window.location.pathname,
    avatar: "monsterid",
    placeholder: "评论一下我的文章吧~",
    recordIP: true,
  });
  const infoEle = document.querySelector("#vcomments .info");
  if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
    infoEle.childNodes.forEach(function (item) {
      item.parentNode.removeChild(item);
    });
  }
</script>
<style>
  #vcomments-box {
    padding: 5px 30px;
  }

  @media screen and (max-width: 800px) {
    #vcomments-box {
      padding: 5px 0px;
    }
  }

  #vcomments-box #vcomments {
    background-color: #fff;
  }

  .v .vlist .vcard .vh {
    padding-right: 20px;
  }

  .v .vlist .vcard {
    padding-left: 10px;
  }
</style>

 
     
</article>

</section>
      <footer class="footer">
  <div class="outer">
    <ul>
      <li>
        Copyrights &copy;
        2015-2020
        <i class="ri-heart-fill heart_icon"></i> AURORA_ZXH
      </li>
    </ul>
    <ul>
      <li>
        
        
        
        Powered by <a href="https://hexo.io" target="_blank">Hexo</a>
        <span class="division">|</span>
        Theme - <a href="https://github.com/Shen-Yu/hexo-theme-ayer" target="_blank">Ayer</a>
        
      </li>
    </ul>
    <ul>
      <li>
        
        
        <span>
  <span><i class="ri-user-3-fill"></i>Visitors:<span id="busuanzi_value_site_uv"></span></s>
  <span class="division">|</span>
  <span><i class="ri-eye-fill"></i>Views:<span id="busuanzi_value_page_pv"></span></span>
</span>
        
      </li>
    </ul>
    <ul>
      
    </ul>
    <ul>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
      </li>
    </ul>
  </div>
</footer>
      <div class="float_btns">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>

<div class="todark" id="todark">
  <i class="ri-moon-line"></i>
</div>

      </div>
    </main>
    <aside class="sidebar on">
      <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/avatar.jpg" alt="AURORA"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="http://aurora-zxh.lofter.com/" target="_blank" rel="noopener">随记</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/link">友链</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
    </aside>
    <script>
      if (window.matchMedia("(max-width: 768px)").matches) {
        document.querySelector('.content').classList.remove('on');
        document.querySelector('.sidebar').classList.remove('on');
      }
    </script>
    <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.png">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wxpay.png">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
    
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/lazyload.min.js"></script>

<!-- Tocbot -->


<script src="/js/tocbot.min.js"></script>

<script>
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer: 'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto'
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">
<script src="https://cdn.jsdelivr.net/npm/justifiedGallery@3.7.0/dist/js/jquery.justifiedGallery.min.js"></script>

<script src="/dist/main.js"></script>

<!-- ImageViewer -->

<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.min.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>

<!-- MathJax -->

<!-- Katex -->

<!-- busuanzi  -->


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<!-- ClickLove -->

<!-- ClickBoom1 -->

<!-- ClickBoom2 -->

<!-- CodeCopy -->


<link rel="stylesheet" href="/css/clipboard.css">

<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<script>
  function wait(callback, seconds) {
    var timelag = null;
    timelag = window.setTimeout(callback, seconds);
  }
  !function (e, t, a) {
    var initCopyCode = function(){
      var copyHtml = '';
      copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
      copyHtml += '<i class="ri-file-copy-2-line"></i><span>COPY</span>';
      copyHtml += '</button>';
      $(".highlight .code pre").before(copyHtml);
      $(".article pre code").before(copyHtml);
      var clipboard = new ClipboardJS('.btn-copy', {
        target: function(trigger) {
          return trigger.nextElementSibling;
        }
      });
      clipboard.on('success', function(e) {
        let $btn = $(e.trigger);
        $btn.addClass('copied');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-checkbox-circle-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPIED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-checkbox-circle-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
      clipboard.on('error', function(e) {
        e.clearSelection();
        let $btn = $(e.trigger);
        $btn.addClass('copy-failed');
        let $icon = $($btn.find('i'));
        $icon.removeClass('ri-file-copy-2-line');
        $icon.addClass('ri-time-line');
        let $span = $($btn.find('span'));
        $span[0].innerText = 'COPY FAILED';
        
        wait(function () { // 等待两秒钟后恢复
          $icon.removeClass('ri-time-line');
          $icon.addClass('ri-file-copy-2-line');
          $span[0].innerText = 'COPY';
        }, 2000);
      });
    }
    initCopyCode();
  }(window, document);
</script>


<!-- CanvasBackground -->


    
  </div>
</body>

</html>